import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_base/page/common/common_style.dart';
import 'package:flutter_base/viewmodel/login/login_vm.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';

import '../../utils/navigator_utils.dart';

///
/// @DIR_PATH：lib/page/login
/// @TIME：2024/6/11 21:21
/// @AUTHOR：starr
/// 注册界面

class RegisterPage extends StatefulWidget {
  const RegisterPage({super.key});

  @override
  State<StatefulWidget> createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage>
    with TickerProviderStateMixin, WidgetsBindingObserver {
  //渐变动画
  late AnimationController _fadeAnimationController;
  late bool _isPwdObscureText = true;//是否显示密码
  late bool _isPwdAgainObscureText = true;//是否显示确认密码

  //文本输入框控制器
  final TextEditingController _userNameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final TextEditingController _passwordAgainController = TextEditingController();
  //焦点控制器
  final FocusNode _userNameFocusNode = FocusNode();
  final FocusNode _passwordFocusNode = FocusNode();
  final FocusNode _passwordAgainFocusNode = FocusNode();

  LoginViewModel viewModel = LoginViewModel();
  @override
  void initState() {
    super.initState();
    //添加监听
    WidgetsBinding.instance.addObserver(this);
    _fadeAnimationController = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 500));

    _fadeAnimationController.addStatusListener((status) {});
    //重复执行动画
    _fadeAnimationController.forward();
  }

  @override
  void dispose() {
    //解绑
    WidgetsBinding.instance.removeObserver(this);
    _fadeAnimationController.dispose();
    super.dispose();
  }

  bool _showInputBg = false;

  //应用尺寸改变时回调
  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    /*
     *Frame是一次绘制过程，称其为一帧，
     * Flutter engine受显示器垂直同步信号"VSync"的驱使不断的触发绘制，
     *Flutter可以实现60fps（Frame Per-Second），
     * 就是指一秒钟可以触发60次重绘，FPS值越大，界面就越流畅。
     */
    WidgetsBinding.instance.addPostFrameCallback((_) {
      //注意，不要在此类回调中再触发新的Frame，这可以会导致循环刷新。
      setState(() {
        ///获取底部遮挡区域的高度
        if (MediaQuery.of(context).viewInsets.bottom == 0) {
          //关闭键盘 启动logo动画反向执行 0.0 -1.0
          // logo 布局区域显示出来
          setState(() {
            _showInputBg = false;
          });
        } else {
          //显示键盘 启动logo动画正向执行 1.0-0.0
          // logo布局区域缩放隐藏
          setState(() {
            _showInputBg = true;
          });
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Stack(
      children: [
        //第一部分 第一层 渐变背景
        buildBackground(),
        //第二部分 第二层 气泡
        // BubbleWidget(),
        //第三部分 高斯模糊
        buildBlureWidget(),
        //第四部分 顶部的文字 logo 的Hero动画
        buildHeroLogo(context),
        //第五部分 输入框与按钮
        FadeTransition(
          opacity: _fadeAnimationController,
          child: buildColumn(context),
        ),
        //第六部分 左上角的关闭按钮
        Positioned(
          top: 44,
          left: 10,
          child: CloseButton(
            onPressed: () {
              NavigatorUtils.pop(context);
            },
          ),
        )
      ],
    ));
  }

  //第一部分 第一层 渐变背景
  Container buildBackground() {
    return Container(
      decoration: BoxDecoration(
        //线性渐变
        gradient: LinearGradient(
          //渐变角度
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          //渐变颜色组
          colors: [
            Colors.lightBlue.withOpacity(0.3),
            Colors.lightBlueAccent.withOpacity(0.3),
            Colors.blue.withOpacity(0.3),
          ],
        ),
      ),
    );
  }

  //第三部分 高斯模糊
  Widget buildBlureWidget() {
    return BackdropFilter(
      filter: ImageFilter.blur(sigmaX: 0.3, sigmaY: 0.3),
      child: Container(
        color: Colors.white.withOpacity(0.1),
      ),
    );
  }

//第四部分 顶部的文字 logo 的Hero动画
  Positioned buildHeroLogo(BuildContext context) {
    return Positioned(
      top: 120,
      left: 45,
      child: Row(
        children: [
          Hero(
            tag: "loginTag",
            child: Material(
              color: Colors.transparent,
              child: ClipOval(
                child: InkWell(
                  onTap: () {
                    Navigator.of(context).pop();
                  },
                  child: Image.asset(
                    "assets/images/2.0x/app_icon.png",
                    fit: BoxFit.fill,
                    width: 44,
                    height: 44,
                  ),
                ),
              ),
            ),
          ),
          const SizedBox(
            width: 16,
          ),
          const Text(
            'Hello Flutter',
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Colors.blue,
              fontSize: 40.0,
              fontWeight: FontWeight.w900,
            ),
          ),
        ],
      ),
    );
  }

  //第五部分输入框
  //第五部分 输入框与按钮
  Widget buildColumn(BuildContext context) {
    return GestureDetector(
      onTap: () {
        hidenKeyBoard();
      },
      child: Container(
        color:
            _showInputBg ? Colors.white.withOpacity(0.5) : Colors.transparent,
        padding: const EdgeInsets.all(44),
          child: ChangeNotifierProvider(
              create: (context) {
                return viewModel;
              },
              child: buildInputColumn(context))),
    );
  }

  Widget buildInputColumn(BuildContext context) {
    return Consumer<LoginViewModel>(builder: (context, vm, child) {
      return Column(
        //子Widget 底部对齐
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          commonInput(
            hintText: '用户名',
            icon: Icon(Icons.mail_outline),
            controller: _userNameController,
            focusNode: _userNameFocusNode,
            isObscure: false,
            onSubmitted: (value) {
              checkUserName(value);
              vm.registerInfo.name = value;
              //焦点切换
              _userNameFocusNode.unfocus();
              _passwordAgainFocusNode.unfocus();
              FocusScope.of(context).requestFocus(_passwordFocusNode);
            },
          ),
          const SizedBox(
            height: 10.0,
          ),
          Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: <Widget>[
              passwordInput(
                hintText: '密码',
                icon: const Icon(Icons.lock_outline),
                onObscurePress: () {
                  setState(() {
                    _isPwdObscureText = !_isPwdObscureText;
                  });
                },
                controller: _passwordController,
                focusNode: _passwordFocusNode,
                isObscure: _isPwdObscureText,
                onSubmitted: (value) {
                  checkPassword(value);

                  vm.registerInfo.password = value;
                  //焦点切换
                  _passwordFocusNode.unfocus();
                  _userNameFocusNode.unfocus();
                  FocusScope.of(context).requestFocus(_passwordAgainFocusNode);
                },
              ),
              const SizedBox(
                height: 10.0,
              ),
            ],
          ),
          passwordInput(
            hintText: '确认密码',
            icon: const Icon(Icons.lock_outline),
            onObscurePress: () {
              setState(() {
                _isPwdAgainObscureText = !_isPwdAgainObscureText;
              });
            },
            controller: _passwordAgainController,
            focusNode: _passwordAgainFocusNode,
            isObscure: _isPwdAgainObscureText,
            onSubmitted: (value) {
              checkPassword(value);
              vm.registerInfo.rePassword = value;
              //隐藏键盘
              hidenKeyBoard();
            },
          ),
          const SizedBox(
            height: 20.0,
          ),
          SizedBox(
            width: double.infinity,
            height: 60,
            child: ElevatedButton(
              onPressed: () {
                submitLoginFunction();
              },
              child: const Text("注册"),
            ),
          ),
        ],
      );
    });
  }

  void hidenKeyBoard() {
    //隐藏键盘
    SystemChannels.textInput.invokeMethod('TextInput.hide');
    _passwordFocusNode.unfocus();
    _userNameFocusNode.unfocus();
    _passwordAgainFocusNode.unfocus();
  }

  void checkPassword(String value) {
    if (value.trim().isEmpty) {
      showToast("请输入密码");
      return;
    }
  }

  void checkUserName(String value) {
    if (value.trim().isEmpty) {
      showToast("请输入用户账号");
      return;
    }
  }

  ///登录
  void submitLoginFunction() async {
    //隐藏键盘
    hidenKeyBoard();

    //获取用户输入的内容
    String userName = _userNameController.text.trim();
    String password = _passwordController.text.trim();
    //校验
    checkUserName(userName);
    checkPassword(password);
    viewModel.registerInfo.name = userName;
    viewModel.registerInfo.password = password;
    viewModel.registerInfo.rePassword = _passwordAgainController.text.toString();

    //注册成功回到登录页面
    viewModel.register().then((value) {
      if(value == true){
        showToast("注册成功");
        NavigatorUtils.pop(context);
      }
    });
  }
}
